<template>
  <view class="invite-share">
    <view class="invite-bg" />
    <canvas
      class="canvas-share"
      canvas-id="shareCanvas"
      :style="{
        height: `calc((100vw - 32px) / 343 * 535 + 48px)`,
      }"
      @tap="onCloseSharePopup"
    ></canvas>
    <view class="bottom">
      <view class="save-btn" @tap="saveImage">
        <text>保存海报图片</text>
      </view>
      <view>
        <button class="share-btn" open-type="share" hover-class="none">
          转发微信好友
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      data: {},
      shareImg: "",
      portrait: {},
      qrcode: "",
      qrcodeImg: "",
      sharePicUrl: "",
      userInfo: {},
      hasUserInfo: false,
      canIUseGetUserProfile: false,
      windowHeight: 0,
      avatarImg: "",
    };
  },
  onload() {
    const { windowHeight } = uni.getSystemInfoSync();
    this.windowHeight = windowHeight;
    this.getQrcode();
  },
  methods: {
    // 获取二维码图片
    getQrcode() {
      // http.request({
      //   url: "/wx-userc/userinfo/poster/info.json",
      //   success: ({ data: { data, flag, message } }) => {
      //     if (flag) {
      //       this.data = data;

      //     } else {
      //       message && toast(message);
      //     }
      //   },
      // });
      Promise.all([
        new Promise(this.requestQrbg),
        new Promise(this.requestQrcode),
        new Promise(this.requestAvatar),
      ])
        .then(this.drawCanvas.bind(this))
        .catch(() => {
          uni.hideLoading();
          toast("生成图片失败，请重试", false);
        });
    },
    onShareAppMessage() {
      return {
        title: "邀请好友",
        content: "邀请好友",
        // imageUrl: 'https://talk-resource.oss-cn-hangzhou.aliyuncs.com/wxapplet/share-bg.png',
        path: `/pages/login/poster/index?${this.data.params}`,
      };
    },
    requestQrbg(resolve, reject) {
      if (this.qrcode) {
        resolve(this.qrcode);
      }
      let url = "";
      url =
        "https://tse1-mm.cn.bing.net/th/id/OIP-C.ZeQ5h5qmFJdYmGKtrR-I9gAAAA?pid=ImgDet&rs=1";

      uni.downloadFile({
        url,
        success: (res) => {
          if (
            res.statusCode === 200 &&
            res.tempFilePath &&
            !/\.html?$/i.test(res.tempFilePath) &&
            res.errMsg === "downloadFile:ok"
          ) {
            this.qrcode = res.tempFilePath;
            resolve(this.qrcode);
          } else {
            reject();
          }
        },
        fail: () => {
          reject();
        },
      });
    },
    saveImage() {
      uni.saveImageToPhotosAlbum({
        filePath: this.shareImg, //下载后的临时路径
        success: () => {
          uni.hideLoading();
          uni.showToast({
            title: "保存成功！",
          });
        },
      });
    },
    requestQrcode(resolve, reject) {
      if (this.qrcode) {
        resolve(this.qrcode);
      }
      let url = this.data.qrCodeUrl;
      uni.downloadFile({
        url,
        success: (res) => {
          if (
            res.statusCode === 200 &&
            res.tempFilePath &&
            !/\.html?$/i.test(res.tempFilePath) &&
            res.errMsg === "downloadFile:ok"
          ) {
            this.qrcode = res.tempFilePath;
            resolve(this.qrcode);
          } else {
            reject();
          }
        },
        fail: () => {
          reject();
        },
      });
    },
    requestAvatar(resolve, reject) {
      if (this.avatarImg) {
        resolve(this.avatarImg);
      }
      let url = this.data.userWxAvatar;
      uni.downloadFile({
        url,
        // eslint-disable-next-line unicorn/prevent-abbreviations
        success: (res) => {
          if (
            res.statusCode === 200 &&
            res.tempFilePath &&
            !/\.html?$/i.test(res.tempFilePath) &&
            res.errMsg === "downloadFile:ok"
          ) {
            this.avatarImg = res.tempFilePath;
            resolve(this.avatarImg);
          } else {
            reject();
          }
        },
        fail: () => {
          reject();
        },
      });
    },
    handleSave() {
      toast("正在生成图片...");
      if (this.qrcode && this.qrcodeImg) {
        this.drawCanvas([this.qrcode, this.qrcodeImg]);
      } else {
        Promise.all([
          new Promise(this.requestQrbg),
          new Promise(this.requestQrcode),
          new Promise(this.requestAvatar),
        ])
          .then(this.drawCanvas.bind(this))
          .catch(() => {
            uni.hideLoading();
            toast("生成图片失败，请重试", false);
          });
      }
    },
    mkImg() {
      setTimeout(() => {
        uni.canvasToTempFilePath({
          canvasId: "shareCanvas",
          width: 750,
          height: 1447,
          quality: 1,
          fileType: "png",
          // eslint-disable-next-line unicorn/prevent-abbreviations
          success: (res) => {
            uni.hideLoading();
            this.shareImg = res.tempFilePath;
            this.portrait = undefined;
            this.qrcode = undefined;
          },
          fail: () => {
            uni.hideLoading();
            uni.showLoading({
              title: "生成图片失败，请重试",
            });
          },
        });
      }, 300);
    },
    measureMaxLength(context, text, max) {
      if (context.measureText(text).width > max) {
        let n = text.length;
        for (; n > 0; n -= 1) {
          const temporary = `${text.slice(0, n)}...`;
          if (context.measureText(temporary).width <= max) {
            return temporary;
          }
        }
      } else {
        return text;
      }
    },
    getMaxLength(context, text, max) {
      return context.measureText(text).width * 1.3 > max
        ? context.measureText(text).width * 1.3
        : max;
    },
    drawCanvas(imgs) {
      if (imgs) {
        const context = uni.createCanvasContext("shareCanvas");
        const imgUrl = imgs[0];
        let scaleWidth = (wx.getSystemInfoSync().windowWidth - 32) / 343;

        context.drawImage(
          imgUrl,
          16,
          24,
          wx.getSystemInfoSync().windowWidth - 32,
          scaleWidth * 535
        );

        if (this.data.name) {
          context.setFillStyle("#000");
          context.font = "12px PingFangSC-Medium, sans-serif";
          context.fillText(
            this.data.name,
            scaleWidth * 122,
            scaleWidth * 490 + 24
          );
        }

        if (imgs.length >= 2 && imgs[1]) {
          context.drawImage(
            imgs[1],
            scaleWidth * 271,
            scaleWidth * 467,
            scaleWidth * 60,
            scaleWidth * 60
          );
        }

        if (imgs.length >= 3 && imgs[2]) {
          this.circleImg(
            context,
            imgs[2],
            scaleWidth * 98,
            scaleWidth * 478 + 24,
            scaleWidth * 9
          );
          // context.drawImage(imgs[2], scaleWidth*98,  scaleWidth*478+24, scaleWidth * 18, scaleWidth * 18);
        }
        context.draw(false, this.mkImg);
      }
    },
    circleImg(context, img, x, y, r) {
      // 如果在绘制图片之后还有需要绘制别的元素，需启动 save() 、restore() 方法，否则 clip() 方法会导致之后元素都不可见
      //    save()：保存当前 Canvas 画布状态
      // restore()：恢复到保存时的状态
      let d = r * 2;
      let cx = x + r;
      let cy = y + r;
      context.arc(cx, cy, r, 0, 2 * Math.PI);
      context.strokeStyle = "#FFFFFF"; // 设置绘制圆形边框的颜色
      context.stroke(); // 绘制出圆形，默认为黑色，可通过 ctx.strokeStyle = '#FFFFFF'， 设置想要的颜色
      context.clip();
      context.drawImage(img, x, y, d, d);
      /* ctx.restore(); */
    },
  },
};
</script>

<style lang="less">
.safe-area {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
.invite-share {
  display: flex;
  flex-direction: column;
  width: 100vw;
  // height: 100vh;
  background-color: #f9f9f9;
  .invite-bg {
    width: 100%;
    height: 100%;
    background-image: url(https://z1.ax1x.com/2023/10/27/pieC3Of.png);
    background-size: cover;
    position: absolute;
    top: 0;
  }

  .bottom {
    position: fixed;
    display: flex;
    flex-direction: row;
    align-items: center;
    bottom: 52rpx;
    margin-top: 36rpx;
    padding: 0 64rpx;
    z-index: 9999;
    .safe-area;
    .save-btn {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 46rpx;
      width: 288rpx;
      height: 96rpx;
      background: transparent;
      border-radius: 48rpx;
      border: 2rpx solid #3f60fc;
      text {
        font-size: 32rpx;
        font-weight: 500;
        color: #3f60fc;
        line-height: 44rx;
      }
    }
    .share-btn {
      justify-content: center;
      align-items: center;
      padding: 0;
      width: 288rpx;
      height: 96rpx;
      border-radius: 48rpx;
      background: #3f60fc;
      line-height: 96rpx;
      font-size: 32rpx;
      font-weight: 500;
      color: #ffffff;
    }
  }

  .canvas-share {
    width: 100vw;
    height: 90vh;
  }
}
</style>
